<?php
class Core_System_Mapper
	extends Core_Db_Mapper_Abstract 
{
	
	public static function fetchById(Core_System $sys)
	{	
		if (null == $sys->getId())
		{
			throw new Core_Model_System_Exception('ID Not Set');
		}
		
		$sysTable	= new Core_System_Table();
		$select		= $sysTable->select()
							->where('id = ?', $sys->getId());
							
		$key		= md5('system:' . $sys->getId());	
		$bookKey	= md5('systemBooks:' . $sys->getId());
		
		if (!($row = self::$_cache->load($key)))
		{
			$row		= $sysTable->fetchRow($select);			
			$bookTable	= new Core_Books_Table();
			$books		= $row->findDependentRowset($bookTable)->toArray();
			
			if (count($row) > 0)
			{
				self::$_cache->save($row, $key, array('System'));
				self::$_cache->save($books, $bookKey, array('System', 'Books'));
			}	
		}
		else
		{
			$books = self::$_cache->load($bookKey);
		}

		if (count($row) < 1)
		{
			throw new Core_Model_System_Exception('Invalid System ID');
		}
		
		$sys->setOptions($row->toArray());
		self::mapBooks($sys, $books);
	}
	
	public static function fetchAll()
	{
		$sysTable	= new Core_System_Table();
		$key		= md5('allsystems');	
		$bookKey	= md5('allsystemBooks');
		
		if (!($res = self::$_cache->load($key)))
		{
			$bookTable	= new Core_Books_Table();	
			$res		= $sysTable->fetchAll();
			foreach($res as $row)
			{ 		
				$books[$row->id]		= $row->findDependentRowset($bookTable)->toArray();
			}
			
			self::$_cache->save($res, $key, array('System'));
			self::$_cache->save($books, $bookKey, array('System', 'Books'));
		}
		else
		{
			$books = self::$_cache->load($bookKey);
		}
		
		$ret	= array();
		foreach($res as $row)
		{
			$sys	= new Core_System($row->toArray());
			
			self::mapBooks($sys, $books[$sys->getId()]);

			$ret[]	= $sys;				
		}
		
		return $ret;
	}
	
	protected static function mapBooks(Core_System $sys, array $sysBooks)
	{
		foreach ($sysBooks as $book)
		{
			$sys->addBook(new Core_Book(array('id' => $book['id'],
											'systemId' => $book['sys_id'],
											'name' => $book['book'],
											'descp' => $book['descp'])));	
		}	
	}
}